<template>
  <div id="wrapper" class="house-analysis-container">
    <div id="page-wrapper">
      <div id="page-inner">
        <div class="row">
          <div class="col-md-12">
            <h2>季度数据分析</h2>
            <ol class="breadcrumb">
              <li>
                请选择时间:
                <el-date-picker
                    v-model="selectedDate"
                    type="date"
                    placeholder="选择日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd"
                    class="date-picker"
                    @change="handleDateChange"
                >
                </el-date-picker>
              </li>
            </ol>
          </div>
        </div>

        <div class="row">
          <ul id="total" class="um-page-tabs">
            <li
                v-for="item in totalData"
                :key="item.id"
                :class="{ 'um-page-tab': true, 'active-tab': tag === item.id }"
                :style="{ width: '50px', 'min-width': '162px' }"
                @click="loadData(item, selectedDate)"
                :id="item.id"
            >
              <div class="um-page-title">{{ item.title }}</div>
              <div class="um-page-value">{{ item.totalData }}</div>
              <div class="um-page-rate">
                <span class="um-page-rate-name">{{ getNodeType(item) }}</span>
                <span class="um-page-rate-value"></span>
                <span class="um-page-rate-icon"><i class="iconfont"></i></span>
              </div>
            </li>
          </ul>
        </div>

        <div class="row">
          <div class="col-md-12">
            <div class="panel panel-default">
              <div class="panel-body">
                <div id="main" style="width: 100%; height: 400px;"></div>
                <div v-if="!selectedDate" class="initial-tip">
                  <p>请选择日期以查看数据</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: 'QuarterAnalysis',
  data() {
    return {
      selectedDate: '',
      tag: '',
      idList: [],
      totalData: [],
      myChart: null,
      isDataLoaded: false
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    // 确保组件销毁时释放ECharts资源
    if (this.myChart) {
      this.myChart.dispose()
      this.myChart = null
    }
  },
  methods: {
    // 初始化图表
    initChart() {
      if (this.myChart) this.myChart.dispose()

      this.myChart = echarts.init(document.getElementById('main'))
      this.myChart.setOption({
        title: { text: '房源数量趋势分析', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        toolbox: { feature: { saveAsImage: {} } },
        xAxis: { type: 'category', boundaryGap: false, data: [] },
        yAxis: { type: 'value', name: '房源数量' },
        series: [{
          name: '房源数量',
          type: 'line',
          data: [],
          lineStyle: { width: 2 },
          areaStyle: {} // 保留区域填充样式
        }]
      })
    },

    // 日期选择处理
    handleDateChange(val) {
      this.selectedDate = val

      if (val) {
        this.loadTotalData(val)
        this.showAnalysis(this.tag || 'dayCount', val)
        this.isDataLoaded = true
      } else {
        this.initChart()
        this.totalData = []
        this.isDataLoaded = false
      }
    },

    // 加载统计卡片数据
    loadTotalData(date) {
      const url = `searchByJj${date ? `?thisEntryDate=${date}` : ''}`

      this.$request.get(url).then(res => {
        if (res.data && res.data.length > 0) {
          this.totalData = res.data
          this.tag = this.tag || res.data[0].id
          this.idList = this.idList.length ? this.idList : res.data.map(item => item.id)
        }
      }).catch(console.error)
    },

    // 切换数据标签
    loadData(data, date) {
      if (!date) return

      this.idList.forEach(id => {
        const el = document.getElementById(id)
        el && el.classList.remove('active-tab')
      })

      this.tag = data.id
      const currentEl = document.getElementById(data.id)
      currentEl && currentEl.classList.add('active-tab')

      this.showAnalysis(this.tag, date)
    },

    // 获取节点类型文本
    getNodeType(item) {
      if (item.id === 'monCount') {
        return item.is_monthend === 'Y' ? '月节点' : '非月节点'
      } else if (item.id === 'yearCount') {
        return item.is_yearend === 'Y' ? '年节点' : '非年节点'
      }
      return ''
    },

    // 显示分析图表
    showAnalysis(tag, date) {
      if (!date) return

      const url = `searchByData?tag=${tag}&thisEntryDate=${date}`
      this.myChart.showLoading()

      this.$request.get(url).then(res => {
        this.myChart.hideLoading()

        if (res.data && res.data.length > 0) {
          const xnames = res.data.map(item => item.date)
          const ynums = res.data.map(item => item.activeCount)

          // 完整更新图表配置，保留所有原有配置项
          this.myChart.setOption({
            xAxis: { data: xnames },
            series: [{
              name: '房源数量',
              type: 'line',
              data: ynums,
              lineStyle: { width: 2 },
              areaStyle: {} // 确保区域填充样式保留
            }]
          })
        } else {
          alert('数据为空，无法生成图表')
        }
      }).catch(err => {
        this.myChart.hideLoading()
        console.error('图表数据请求失败', err)
        alert('图表请求数据失败!请选择合适时间')
      })
    },

    // 生成七天日期范围（后端处理时可移除）
    generateSevenDays(dateStr) {
      const dates = []
      const date = new Date(dateStr)

      for (let i = 6; i >= 0; i--) {
        const d = new Date(date)
        d.setDate(date.getDate() - i)
        dates.push(`${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`)
      }

      return dates.reverse()
    }
  },
  watch: {
    selectedDate(newVal) {
      if (newVal) {
        this.loadTotalData(newVal)
        this.showAnalysis(this.tag || 'dayCount', newVal)
      }
    }
  }
}
</script>

<style scoped>
/* 样式保持不变 */
.house-analysis-container {
  height: 100vh;
}

.um-page-tabs {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  padding: 0;
  margin: 0 -10px;
}

.um-page-tab {
  flex: 0 0 calc(25% - 20px);
  margin: 10px;
  padding: 15px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.um-page-tab.active-tab {
  background-color: #42b983;
  border-color: #42b983;
  color: white;
}

.um-page-title {
  font-size: 14px;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.um-page-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}

.um-page-rate {
  font-size: 12px;
  color: #6c757d;
}

.date-picker {
  width: 200px;
  margin-left: 10px;
}

.initial-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #999;
  font-size: 16px;
}

@media (max-width: 768px) {
  .um-page-tab {
    flex: 0 0 calc(50% - 20px);
  }
}

@media (max-width: 480px) {
  .um-page-tab {
    flex: 0 0 100%;
  }
}
</style>